package com.syedu.day20;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 * @author Administrator
 * @Description 文件上传服务端
 * @createTime 2022/4/12 13:35
 */
public class FileUploadServer {
    public static void main(String[] args) {
        //1.创建服务端套接字对象
        try (ServerSocket server = new ServerSocket(9999)) {
            while (true) {
                //2.建立连接
                Socket client = server.accept();
                //多线程
                new Thread(() -> {
                    //3.创建流对象,先读,后写
                    //a.读取客户端发送过来数据的输入流
                    //b.写入服务器磁盘使用的输出流
                    PrintWriter writer = null;
                    try (BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
                         BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:\\upload\\" + UUID.randomUUID() + ".zip"))) {
                        writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()),true);
                        //4.读写数据
                        byte[] buf = new byte[3 * 1024];
                        int len;
                        while ((len = bis.read(buf)) != -1) {
                            bos.write(buf, 0, len);
                            bos.flush();
                        }
                        //上传完成后向客户端发送一个完成信息
                        writer.println("1");
                    } catch (Exception e) {
                        writer.println("0");
                    }
                    writer.close();
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
